from django.shortcuts import render
from django.http import HttpResponse
import os
from .models import Image
current_path = os.path.abspath(os.path.dirname(__file__))


# Create your views here.
def old_update_image(request):
    if request.method == 'GET':
        return render(request, 'myapp/old_images.html')
    elif request.method == 'POST':
        img = request.FILES.get('imgFile')  # 文件、图片处理时要使用FILES
        if img:
            """"
                这里需要注意一个问题就是，图片名出现重复的情况
            """
            with open(f'{current_path}/static/images/{img}', 'wb') as img_file:
                for chunk in img.chunks():  # 将图片分成块，依次存储
                    img_file.write(chunk)
                    img_file.flush()
                return HttpResponse('图片上传成功！')
        else:
            return HttpResponse('图片上传失败！')


def new_update_image(request):
    if request.method == 'GET':
        return render(request, 'myapp/new_images.html')
    elif request.method == 'POST':
        img = request.FILES.get('imgFile')
        image = Image.objects.create(name=f'{img}', image_path=img)
        if image:
            return HttpResponse('上传图片成功！')
        else:
            return HttpResponse('上传图片失败！')


# 显示图片文件
def show_iamge(request):
    image = Image.objects.get(pk=3)
    return render(request, 'myapp/show_image.html', locals())